// This file contains material supporting section 10.9 of the textbook:
// "Object Oriented Software Engineering" and is issued under the open-source
// license found at www.lloseng.com

/*
 * SimpleClient.java   2001-02-08
 *
 * Copyright (c) 2001 Robert Laganiere and Timothy C. Lethbridge.
 * All Rights Reserved.
 *
 */
package control;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;



import client.AbstractClient;
import client.Message;


public class SimpleClient extends AbstractClient {
	
	private PropertyChangeSupport propertyChangeSupport;
	private PropertyChangeListener listener;
	private static SimpleClient instance = null;

	private Message returnMsg = null;

	
	private SimpleClient(String host, int port) {
		super(host, port);
		propertyChangeSupport = new PropertyChangeSupport(this);
	}

	public static void initClient(String host, int port) {
		if (instance == null) {
			instance = new SimpleClient(host, port);
		}
	}

	public static SimpleClient getInstance() {
		return instance;
	}

	/**
	 * Hook method called after the connection has been closed.
	 */
	protected void connectionClosed() {
		System.out.println("Connection terminated ...");
	}

	/**
	 * Hook method called each time an exception is thrown by the client's
	 * thread that is waiting for messages from the server.
	 * 
	 * @param exception
	 *            the exception raised.
	 */
	protected void connectionException(Exception exception) {
	
		System.out.println(exception);
	}

	/**
	 * Hook method called after a connection has been established.
	 */
	protected void connectionEstablished() {
		System.out.println("Connected To Server Succesfully\n");
	}

	
	/**
	 * Handles a message sent from the server to this client.
	 * 
	 * @param msg
	 *            the message sent.
	 */
	protected synchronized void handleMessageFromServer(Object msg) {
        this.returnMsg = (Message)msg;
		propertyChangeSupport.firePropertyChange("MessageUpdate", this.returnMsg,null );
	}

	public Message getReturnMsg() {
		return returnMsg;
	}

	public void setReturnMsg(Message returnMsg) {
		this.returnMsg = returnMsg;
	}

	public void addPropertyChangeListener(PropertyChangeListener listener) {
		this.listener = listener;
		propertyChangeSupport.addPropertyChangeListener(this.listener);
	}

	public void clearPropertyChangeListener() {
		propertyChangeSupport.removePropertyChangeListener(this.listener);
		//this.returnMsg = null;
	}

}